package com.herr.springboot.self.xxx.common.extend;

import com.herr.springboot.self.xxx.common.constant.APIConstant;
import com.herr.springboot.self.xxx.common.entity.Principal;
import com.herr.springboot.self.xxx.common.exception.UnAuthException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 重要参数解析器
 * @author herr05
 */
@Component
public class PrincipalResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return Principal.class.isAssignableFrom(methodParameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        return getPrincipal();
    }

    private static Principal getPrincipal(){
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Principal principal =new Principal();
        String uid=request.getAttribute(APIConstant.API_UID).toString();
        String usercode=request.getAttribute(APIConstant.API_USERCODE).toString();
        if (StringUtils.isBlank(uid)){
            throw new UnAuthException("uid不能为空");
        }
        principal.setUid(Long.parseLong(uid));
        principal.setUsercode(usercode);
        return principal;
    }
}
